package com.ht.common.core.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES加解密
 */
public class AESUtils {

    private final static Logger log = LoggerFactory.getLogger(AESUtils.class);

    private final static String AES = "AES";

    /**
     * @param source 原始待加密的数据
     * @param key    base64加密后的key
     * @return AES加密后再经base64加密后的数据
     * @throws Exception
     */
    public static String encryptByAES(String source, String key){
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES);
            // AES/CBC/PKCS5Padding "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);//加密
            byte[] encrypted = cipher.doFinal(source.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.getEncoder().encode(encrypted), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.info("AES加密异常:{}", e.getMessage());
            e.printStackTrace();
            return source;
        }
    }

    /**
     * AES解密
     *
     * @param source AES加密后的二进制再由 base64加密后的字符串
     * @param key    base64加密后的key
     * @return 解密后原始数据
     * @throws Exception
     */
    public static String decryptByAES(String source, String key){
        try {
            // "算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(AES);
            byte[] bAry = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec keySpec = new SecretKeySpec(bAry, AES);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);// 解密
            byte[] results = cipher.doFinal(Base64.getDecoder().decode(source));
            return new String(results, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.info("AES解密异常:{}", e.getMessage());
            e.printStackTrace();
            return source;
        }
    }


    public static String getAesKey() throws UnsupportedEncodingException {
        byte[] keys = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return Base64.getEncoder().encodeToString(keys);
    }
    
    public static void main(String[] args) {
		String key="cLhL3TPfMYVMsy75rWQitw==";
		String yw="{\"ppp\":\"4\",\"billCode\":\"3\"}";
		String jm=encryptByAES(yw, key);
		System.out.println(jm);
		String jiem=decryptByAES(jm, key);
		System.out.println(jiem);
	}

}
